/**
 * Created by shawn on 17/8/23.
 */
const koa = require('koa');
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const templating = require('./templating');
const rest = require('./rest');
const staticServer = require('koa-static');
const path = require('path');
const app = new koa();

// 记录URL以及页面执行时间
app.use(async(ctx, next)=>{
    console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
    var  start = new Date().getTime(),
         execTime;
    await next();
    execTime = new Date().getTime() - start;
    ctx.response.set('X-Response-Time', `${execTime}ms`);
});

const isProduction = process.env.NODE_ENV === 'production';

// 处理静态文件
if (!isProduction) {
    app.use(staticServer(path.join(__dirname,'client')));
}

// 解析POST请求
app.use(bodyParser());

// 负责给ctx加上render()来使用Nunjucks
app.use(templating('client',{
    noCache: !isProduction,
    watch: !isProduction
}));

// bind .rest() for ctx
app.use(rest.restify());

// 处理URL路由
app.use(controller());

app.listen(3100);
console.log('app started at port 3100.....');
